package com.rom.tree;

import java.util.Arrays;

/**
 * @author YLNO
 * @version 1.0
 * @date 2023/12/12 16:23
 * 顺序存储二叉树遍历
 */
public class ArrayBinaryTree {

    public static void main(String[] args) {

        int[] arr = {1,2,3,4,5,6,7};
        ArrayTree arrayTree = new ArrayTree(arr);
        System.out.println("前序排序---------------》");
        arrayTree.preOrder(0);
        System.out.println("\n中序排序---------------》");
        arrayTree.infixOrder(0);
        System.out.println("\n后序排序---------------》");
        arrayTree.postOrder(0);
    }
}
class ArrayTree{

    private int[] arr;

    public ArrayTree(int[] arr) {
        this.arr = arr;
    }
    //前序
    public void preOrder(int index){

        if(arr==null || arr.length == 0){
            System.out.println("数组为空");
        }
        System.out.print(arr[index]+"\t");
        //左节点
        if(index*2+1 < arr.length){
            preOrder(index*2+1);
        }
        if(index*2+2<arr.length){
            preOrder(index*2+2);
        }
    }
//    中序
    public void infixOrder(int index){

        if(arr==null || arr.length == 0){
            System.out.println("数组为空");
        }
        //左节点
        if(index*2+1 < arr.length){
            infixOrder(index*2+1);
        }
        System.out.print(arr[index]+"\t");
        if(index*2+2<arr.length){
            infixOrder(index*2+2);
        }
    }

    //    后序
    public void postOrder(int index){

        if(arr==null || arr.length == 0){
            System.out.println("数组为空");
        }
        //左节点
        if(index*2+1 < arr.length){
            postOrder(index*2+1);
        }
        if(index*2+2<arr.length){
            postOrder(index*2+2);
        }
        System.out.print(arr[index]+"\t");
    }

    public int[] getArr() {
        return arr;
    }

    public void setArr(int[] arr) {
        this.arr = arr;
    }

    @Override
    public String toString() {
        return "ArrayTree{" +
                "arr=" + Arrays.toString(arr) +
                '}';
    }
}